'use strict';
const crypto = require('crypto');

const uniPush = uniCloud.getPushManager({
	appId: "__UNI__2408CEF"
})
const key = '23dfDwe23sdw45gFswscvF4dw3456h13'

exports.main = async (event) => {
	let obj = JSON.parse(event.body);
	let cid = obj.cid;
	let timestamp = obj.timestamp;
	let sign = obj.sign;
	
	if(cid == null || cid == ''){
		return {"errCode": "cid-error", "errMsg": "cid cannot be empty"};
	}
	
	if(timestamp == null || timestamp == ''){
		return {"errCode": "timestamp-error", "errMsg": "timestamp cannot be empty"};
	}
	
	// try{
	// 	let time = new Date(timestamp).getTime();
	// 	if(new Date().getTime() - time > 1000 * 60 * 10){
	// 		return {"errCode": "timestamp-error", "errMsg": "Timestamp has expired"};
	// 	}
	// }catch(e){
	// 	return {"errCode": "timestamp-error", "errMsg": "timestamp cannot be empty"};
	// }
	
	const md5 = crypto.createHash('md5');
	let cryptostr = md5.update(cid + timestamp + key).digest('hex').toLocaleLowerCase();
	if(sign != cryptostr){
		return {"errCode": "sign-error", "errMsg": "sign error"};
	}
	
	const res = await uniPush.sendMessage({
		"push_clientid": obj.cid,
		"title": obj.title,
		"content": obj.content,
		"payload": obj.data,
		"force_notification": true,
		"request_id": obj.request_id
	})
	return res;
};
